import { deleteTopic, getTopicById } from '~/server/database/services/topicService'
import authMiddleware from '~/server/middleware/auth'

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event)
    
    const id = getRouterParam(event, 'id')
    
    if (!id || isNaN(parseInt(id))) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的题目ID'
      })
    }

    // 从event.context中获取用户信息
    const user = event.context.user
    
    // 检查题目是否存在并验证权限
    const existingTopic = await getTopicById(parseInt(id))
    if (!existingTopic) {
      throw createError({
        statusCode: 404,
        statusMessage: '题目不存在'
      })
    }
    
    // 检查是否有权限删除此题目
    if (existingTopic?.dataValues.submitterId !== user.id) {
      throw createError({
        statusCode: 403,
        statusMessage: '无权删除此题目'
      })
    }

    // 删除题目
    const success = await deleteTopic(parseInt(id))

    if (!success) {
      throw createError({
        statusCode: 404,
        statusMessage: '题目不存在'
      })
    }

    return {
      success: true,
      message: '题目删除成功'
    }
  } catch (error) {
    console.error('删除题目失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: '删除题目失败'
    })
  }
})
